package com.aaa.exception;

import com.aaa.entity.ResultCode;
import com.aaa.entity.ResultMsg;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.ClientAlreadyExistsException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

public class OauthResponseExceptionTranslator implements WebResponseExceptionTranslator {
    //转换异常.响应数据
    //UnsupportedGrantTypeException：授权类型错误
    //InvalidGrantException: 用户名密码错误
    // InternalAuthenticationServiceException：账号被禁用
    @Override
    public ResponseEntity translate(Exception e) throws Exception {

            ResultMsg resultMsg = null;
            if (e instanceof UnsupportedGrantTypeException) {
                //授权类型错误
                resultMsg = ResultMsg.error(ResultCode.UNSUPPORTED_GRANT_TYPE.getCode(), ResultCode.UNSUPPORTED_GRANT_TYPE.getMsg());
            } else if (e instanceof InvalidGrantException) {
                //用户名密码错误
                resultMsg = ResultMsg.error(ResultCode.BAD_CREDENTIALS.getCode(), ResultCode.BAD_CREDENTIALS.getMsg());
            } else if (e instanceof InternalAuthenticationServiceException) {
                //被禁用
                resultMsg = ResultMsg.error(ResultCode.NO_DISABLED.getCode(), ResultCode.NO_DISABLED.getMsg());
            } else {
                //系统错误
                System.out.println("ddd");
                resultMsg = ResultMsg.error(ResultCode.ERROR.getCode(), ResultCode.ERROR.getMsg());
            }
            return new ResponseEntity<>(resultMsg, HttpStatus.OK);

    }
}
